package com.lej.dataservice.club.login

import com.alibaba.android.arouter.launcher.ARouter
import com.lej.core.base.app
import com.lej.core.base.currentActivity
import com.lej.core.common.CHECK_UNKNOWN
import com.lej.core.common.CHECK_UN_PASS
import com.lej.core.common.PCacheInfo
import com.lej.core.common.userIsLogin
import com.lej.core.daq.DAQEvent
import com.lej.core.provider.imStatusCheckProvider
import com.lej.core.router.CRouter
import com.lej.core.router.CRouter.Companion.navigation
import com.lej.dataservice.club.bean.TipsKey
import com.lej.dataservice.club.http.errorWarning
import com.lej.theme.dialog.ImgAlertPopDialog
import kotlinx.coroutines.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


/**
 * 常用工具类
 */
object LoginStatusExt {
    /**
     * 检测是否已经登录,未登录状态将弹窗提示是否去登录页面
     * @return true:已登录 false:未登录
     */
    suspend fun checkLogin(): Boolean {
        imStatusCheckProvider.checkIMLogin()
        return if (!userIsLogin()) {
            withContext(Dispatchers.Main) {
                suspendCoroutine {
                    popLoginMessage { b -> runCatching { it.resume(b) } }
                }
            }
        } else true
    }

    //弹登录提示弹窗
    private fun popLoginMessage(block: (Boolean) -> Unit) {
        MainScope().launch {
            val tipsBean = TipsKey.go_login.tips()
            ImgAlertPopDialog.show(
                currentActivity!!,
                tipsBean?.title ?: "登录",
                content = tipsBean?.content ?: "需要先登录",
                confirmText = "登录",
                cancelText = "再等等",
                onConfirm = {
                    DAQEvent.to_login.mobEvent("true")
                    CRouter.login.navigation()
                    block(false)
                },
                cancel = {
                    DAQEvent.to_login.mobEvent("false")
                    block(false)
                })
        }
    }


    /**检查人脸SDK是否识别*/
    fun CoroutineScope.checkFace(): Boolean {
        if (PCacheInfo.faceCheckStatus == CHECK_UNKNOWN || PCacheInfo.faceCheckStatus == CHECK_UN_PASS) {
            val tips = if (PCacheInfo.faceCheckStatus == CHECK_UNKNOWN) {
                "大家都完成了真人认证，让他们知道，你也是真实的星探。"
            } else {
                "您的真人认证未通过，重新认证后才可以设置封面哦"
            }
            launch {
                errorWarning(tips, hideCancel = false) {
                    ARouter.getInstance().build(CRouter.face).navigation(currentActivity)
                }
            }
            return false
        }
        return true
    }
}

fun doWhenLogin(block: () -> Unit) {
    MainScope().launch {
        if (LoginStatusExt.checkLogin()) block()
    }
}

///相关测试代码
fun doInDebug(block: () -> Unit) {
    if (app.isDebug) block()
}
